package com.lagou.homework4.no4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 客户端
 */
public class ClientTest {

    public static void main(String[] args) {
        //创建socket类型的对象并提供主机用户名和端口号
        Socket socket = null;
        ObjectOutputStream out = null;
        ObjectInputStream br = null;
        try {
            socket = new Socket("127.0.0.1",8888);
            //使用输入输出流进行通信
            // 实现客户端向服务器发送字符串内容"admin" 和 "123456"
            out = new ObjectOutputStream(socket.getOutputStream());
            User user = new User("admin","123456");
            out.writeObject(user);
            System.out.println("客户端发送数据内容成功！");
            br = new ObjectInputStream(socket.getInputStream());
            try {
                UserMessage userMessage = (UserMessage) br.readObject();
                if(userMessage.getType().equals("success")){
                    System.out.println("登录成功！");
                }else{
                    System.out.println("登录失败！");
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=socket){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
